package main

import (
	"context"
	rentalpb "coolcar/v1/blob/api/gen/v1"
	"coolcar/v1/blob/blob"
	"coolcar/v1/blob/cos"
	"coolcar/v1/blob/dao"
	"coolcar/v1/shared/server"
	"coolcar/v1/shared/zaplog"
	"github.com/namsral/flag"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"google.golang.org/grpc"
	"log"
	"time"
)

var (
	mongodbName = "coolcar"
)

var addr = flag.String("addr", ":8083", "address to listen")
var mongoURI = flag.String("mongo_uri", "mongodb://localhost:27017/?readPreference=primary&ssl=false", "mongo uri")
var cosAddr = flag.String("cos_addr", "https://coolcar-1302389650.cos.ap-shanghai.myqcloud.com", "cos addr")
var cosSecID = flag.String("cos_sec_id", "<SEC_ID>", "cos secret id")
var cosSecKey = flag.String("cos_sec_key", "<SEC_KEY>", "cos secret key")

func main() {
	flag.Parse()
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	sugar, err := zaplog.NewZapLogger()
	if err != nil {
		log.Fatalf("failed to create logger: %v", err)
	}
	defer sugar.Sync()

	mc, err := mongo.Connect(ctx, options.Client().ApplyURI(*mongoURI))
	if err != nil {
		sugar.Fatalf("failed to connect mongodb: %v", err)
	}
	db := mc.Database(mongodbName)

	st, err := cos.NewService(*cosAddr, *cosSecID, *cosSecKey)
	if err != nil {
		sugar.Fatalf("failed to create storage: %v", err)
	}

	sugar.Fatal(server.RunGRPCServer(&server.Config{
		Name: "blob",
		Addr: *addr,
		RegisterFunc: func(g *grpc.Server) {
			rentalpb.RegisterBlobServiceServer(g, &blob.Service{
				Sugar:   sugar,
				Mongo:   dao.NewMongo(db),
				Storage: st,
			})
		},
		Suger: sugar,
	}))
}
